<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2019/3/18
 * Time: 17:15
 */

namespace app\admin\controller;


use common\Ret;
use controller\AuthBasic;
use service\AuthService;
use think\Db;
use think\Log;

class Login extends AuthBasic{

    public function initialize() {
        Log::write("Log:".session('user'));
        if (session('user.id') && $this->request->action() !== 'logout') {
            $this->redirect('@admin');
        }
    }

    public function index() {
        if($this->request->isGet()) {
            return $this->fetch('', ['title' => '用户登录']);
        }
        $captch = $this->request->post('captcha', '');
        if(!captcha_check($captch)) {
            return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg('验证码错误')->toJson();
        }
        $data = [
          "username"    => $this->request->post('username'),
          "password"    => $this->request->post('password')
        ];
        $validate = validate('User');
        if(!$validate->check($data)) {
            return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg($validate->getError());
        }
        $user = Db::name("SysUser")->where("username", $data["username"])->where("valid", 1)->find();
        if(empty($user) || $user["password"] !== md5($data["password"])) {
            return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg("登录账号不存在或密码错误，请重新输入！");
        }
        session("user", $user);
        AuthService::applyAuthNode();
        return $this->ret->setCode(Ret::$_RET_FORWARD)->setMsg("登录成功，正在跳转")->setUrl(url("admin/index/index"))->toJson();
    }
    public function logout() {
        //!empty($_SESSION) && $_SESSION = [];
        //[session_unset(), session_destroy()];
        session("user", null);
        return $this->ret->setCode(Ret::$_RET_FORWARD)->setMsg("退出成功")->setUrl(url('index'))->toJson();
    }
}